#!/usr/bin/env python
#-*- coding: utf-8 -*-
#
# BSD License
# Copyright (c) 2011, Wang Qiang
# All rights reserved.

"""
Class represent a html processor.
"""
import os
import CustomError
from pyquery import PyQuery
from JQSelector.JQSelector import JQSelect, JQSelectPQ

class HtmlProcessor(object):
    """
    class represent a html processor.
    """
    def __init__(self, format):
        """
        Constructor for HtmlProcessor
        @param format: format file used for process this html
        """
        self.format = format
        
    def feedHtml(self, html):
        """
        feed html to processor.
        @param html: target html.
        """
        self.html = html

    def extractFormat(self):
        """
        extract format information from format xml file.
        """
        # Read format xml file
        if not os.path.isfile(self.format):
            # raise the format file error
            raise CustomError.FormatFileError("Cannot find format file: " + \
                                              self.format)
        formatXml = open(self.format, 'r').read()
        contents = JQSelectPQ(formatXml, 'content')
        self.contentFormats = []
        for pqContent in contents:
            type = pqContent.attr('type')
            attr = pqContent.attr('attr')
            composit = pqContent.attr('composit')
            selectStr = pqContent.text()
            self.contentFormats.append((type, attr, composit, selectStr))

    def process(self):
        """
        process the html with the format information
        """
        res = {}
        for type, attr, composit, selectStr in self.contentFormats:
            reshtml = JQSelectPQ(self.html, selectStr)
            if reshtml:
                if attr:
                    res[type] = reshtml[0].attr(attr)
                else:
                    if composit:
                        paras = reshtml
                        res[type] = ""
                        for para in paras:
                            res[type] = res[type] + para.text() + '\n'
                    else:
                        res[type] = reshtml[0].text()
        self.res = res
